package com.jhy.review.paixu;

/**
 * @author go_jhy
 * @create 2022/5/18 - 下午 6:16
 * 归并排序
 */
@SuppressWarnings("all")
public class NiXu {


   
    public static void mergeSort(int arr[]) {
        if(arr == null || arr.length<2){
            return;
        }
        int count = process(arr, 0, arr.length - 1);
        System.out.println(count);
    }
    public static int process(int[] arr,int L,int R) {
        if(L == R) {
            return 0;
        }
        //右移是除以2的原因
        int mid = L+((R - L) >> 1);
        return  process(arr, L, mid)+ process(arr,mid+1,R)+  merge(arr, L, mid, R);
    }

    public static int  merge(int[] arr,int L,int M,int R){
        //先定义一个临时空间
        int[] help = new int[R - L + 1];

        int i = 0;
        int p1 = L;
        int p2 = M+1;
        int count = 0;
        while (p1 <= M && p2 <= R){
            //如果右边的大于左边的了，那么左边的所有都比右边小。所以为0
            count += arr[p1] > arr[p2] ? 0: (R-p2 + 1) ;
            help[i++] = arr[p1] < arr[p2] ? arr[p1++] : arr[p2++];
        }
        while(p1 <= M){
            help[i++] = arr[p1++];
        }
        while(p2 <= R){
            help[i++] = arr[p2++];
        }
        for(int j = 0;j<help.length;j++){
            arr[j+L] = help[j];
        }
        return count;



    }


}
